package cn.wit.db.web;

import cn.wit.db.entity.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {
	private static final Logger logger = LoggerFactory.getLogger(UserController.class);

	@GetMapping("/user-info")
	@ResponseBody
	public AjaxResult getUserInfo(Authentication auth) {
		// 此处authentication是JwtAuthenticationFilter解析token后放入SecurityContextHolder中的
		// 实际中应该根据用户名到数据库查询详细信息，因为登陆后返回的用户信息不一定全（头像、性别什么的）

		logger.debug("auth: {}", auth);
		
		AjaxResult result = AjaxResult.success();
		
		Map<String, Object> map = new HashMap<String, Object>();
		if (auth != null) {
			map.put("user", auth.getPrincipal());
			map.put("roles", 
				auth.getAuthorities().stream()
					.map(a -> a.getAuthority().replace("ROLE_", ""))
					.toArray());
			result.setData(map);
		}

		return result;
	}
}
